import React, { useState, useEffect } from 'react';
import { Button, Col, Form, Input, message, Row, Select, Upload } from 'antd';
import { EyeInvisibleOutlined, EyeTwoTone, UploadOutlined } from '@ant-design/icons';
import md5 from 'js-md5';
import { postRegister } from '@/services/register';
import { getSelectCompetentAuthority } from '@/services/homePage/homePage';
import type { Dispatch } from 'umi';
import { history } from '@@/core/history';
import { connect } from 'umi';
import styles from './index.less';
import { getToken } from '@/utils/storage';

const { Option } = Select;

interface UserRegisterProps {
  dispatch: Dispatch;
}

const UserRegister: React.FC<UserRegisterProps> = (props) => {
  const { dispatch } = props;
  const [form] = Form.useForm();
  const [park, setPark] = useState([]);

  useEffect(() => {
    getSelectCompetentAuthority({ orgType: 'Park' })
      .then((resp) => {
        setPark(resp?.results);
      })
      .catch((error) => {
        throw error;
      });
  }, []);

  const handleSubmit = async () => {
    const values = await form.validateFields();
    console.log(values.file)
    console.log(values.file.file.name)
    console.log(values.file.file.response.results)
    const {
      userAccount,
      password,
      confirmPassword,
      companyName,
      companyAddress,
      unifiedSocialCreditCode,
      orgId,
      userName,
      phone,
      email,
      fileName = values.file.file.name,
      fileUrl = values.file.file.response.results,
      legalPerson,
      legalPersonPhone,
      contactJob,
      contactTwoName,
      contactTwoJob,
      contactTwoPhone,
      industry,
      corporateAccount,
      bankOfDeposit,
    } = values;
    if (password !== confirmPassword) {
      message.error('密码不一致，请重新填写');
      return;
    }
    try {
      const { errorCode } = await postRegister({
        userAccount,
        password: md5(`${password}@zcdx`),
        companyName,
        companyAddress,
        unifiedSocialCreditCode,
        orgId,
        userName,
        phone,
        email,
        fileName,
        fileUrl,
        legalPerson,
        legalPersonPhone,
        contactJob,
        contactTwoName,
        contactTwoJob,
        contactTwoPhone,
        industry,
        corporateAccount,
        bankOfDeposit,
      });
      if (errorCode === 0) {
        message.success('企业注册申请提交成功！请您耐心等待审核');
        dispatch({
          type: 'login/fetchIsLogin',
          payload: false,
        });
        history.push({ pathname: '/' });
      }
    } catch (e) {
      message.error('注册失败,请联系管理员');
    }
  };
  function handleChange(value: any) {
    console.log(`归属下拉选选中 ${value}`);
  }

  const uploadProps = {
    name: 'file',
    maxCount: 1,
    action: `${WEB_DOMAIN.apiDomain}/files/uploadFile`,
    headers: {
      'Access-Token': getToken() || '',
    },
    onChange(info: any) {
      if (info.file.status !== 'uploading') {
        console.log(info.file, info.fileList);
      }
      if (info.file.status === 'done') {
        message.success(`${info.file.name} 文件上传成功。`);
      } else if (info.file.status === 'error') {
        message.error(`${info.file.name} 文件上传失败。`);
      }
    },
  };

  return (
    <div className={styles.UserRegisterWrapper}>
      <Form className={styles.UserRegisterForm} form={form}>
        <Row className={styles.inputItem}>
          <Col className={styles.itemLabel} span={8}>
            用户名：
          </Col>
          <Col className={styles.inputTextContent} span={16}>
            <Form.Item name="userAccount" rules={[{ required: true, message: '用户名不能为空' }]}>
              <Input placeholder="请输入用户名" />
            </Form.Item>
          </Col>
        </Row>
        <Row className={styles.inputItem}>
          <Col className={styles.itemLabel} span={8}>
            密码：
          </Col>
          <Col className={styles.inputTextContent} span={16}>
            <Form.Item
              name="password"
              rules={[
                {
                  required: true,
                  message: '密码不能为空',
                },
              ]}
            >
              <Input.Password
                placeholder="请输入密码"
                iconRender={(visible) => (visible ? <EyeTwoTone /> : <EyeInvisibleOutlined />)}
              />
            </Form.Item>
          </Col>
        </Row>
        <Row className={styles.inputItem}>
          <Col className={styles.itemLabel} span={8}>
            确认密码：
          </Col>
          <Col className={styles.inputTextContent} span={16}>
            <Form.Item
              name="confirmPassword"
              rules={[
                {
                  required: true,
                  message: '请再次输入密码进行确认',
                },
              ]}
            >
              <Input.Password
                placeholder="请再次输入密码"
                iconRender={(visible) => (visible ? <EyeTwoTone /> : <EyeInvisibleOutlined />)}
              />
            </Form.Item>
          </Col>
        </Row>
        <Row className={styles.inputItem}>
          <Col className={styles.itemLabel} span={8}>
            企业名称：
          </Col>
          <Col className={styles.inputTextContent} span={16}>
            <Form.Item name="companyName" rules={[{ required: true, message: '企业名称不能为空' }]}>
              <Input placeholder="请输入企业名称" />
            </Form.Item>
          </Col>
        </Row>
        <Row className={styles.inputItem}>
          <Col className={styles.itemLabel} span={8}>
            企业地址：
          </Col>
          <Col className={styles.inputTextContent} span={16}>
            <Form.Item
              name="companyAddress"
              rules={[{ required: true, message: '企业详细地址不能为空' }]}
            >
              <Input placeholder="请输入企业详细地址" />
            </Form.Item>
          </Col>
        </Row>
        <Row className={styles.inputItem}>
          <Col className={styles.itemLabel} span={8}>
            统一社会信用代码：
          </Col>
          <Col className={styles.inputTextContent} span={16}>
            <Form.Item
              name="unifiedSocialCreditCode"
              rules={[
                { required: true, message: '统一社会信用代码不能为空' },
                {
                  pattern: /^([0-9A-HJ-NPQRTUWXY]{2}\d{6}[0-9A-HJ-NPQRTUWXY]{10}|[1-9]\d{14})$/,
                  message: '统一社会信用代码格式不正确',
                },
              ]}
            >
              <Input placeholder="请输入统一社会信用代码" />
            </Form.Item>
          </Col>
        </Row>
        <Row className={styles.inputItem}>
          <Col className={styles.itemLabel} span={8}>
            营业执照图片：
          </Col>
          <Col className={styles.inputTextContent} span={16}>
            <Form.Item
              name="file"
            >
              <Upload {...uploadProps}>
                <Button icon={<UploadOutlined />}>上传营业执照图片</Button>
              </Upload>
            </Form.Item>
          </Col>
        </Row>
        <Row className={styles.inputItem}>
          <Col className={styles.itemLabel} span={8}>
            归属园区：
          </Col>
          <Col className={styles.inputTextContent} span={16}>
            <Form.Item name="orgId" rules={[{ required: true, message: '归属园区不能为空' }]}>
              <Select
                placeholder="请选择归属园区"
                style={{ width: '100%' }}
                onChange={handleChange}
                allowClear
                className={styles.SelectDept}
              >
                {park?.length &&
                  park?.map((obj) => {
                    return (
                      <Option key={obj.id} value={obj.id}>
                        {obj.orgName}
                      </Option>
                    );
                  })}
              </Select>
            </Form.Item>
          </Col>
        </Row>
        <Row className={styles.inputItem}>
          <Col className={styles.itemLabel} span={8}>
            所属行业：
          </Col>
          <Col className={styles.inputTextContent} span={16}>
            <Form.Item name="industry" rules={[{ required: true, message: '所属行业不能为空' }]}>
              <Select
                placeholder="请选择所属行业"
                style={{ width: '100%' }}
                onChange={handleChange}
                allowClear
                className={styles.SelectDept}
              >
                <Option value="ind_01">工业</Option>
                <Option value="ind_02">服务业</Option>
                <Option value="ind_03">商贸业</Option>
                <Option value="ind_04">建筑业</Option>
                <Option value="ind_05">个体工商户</Option>
              </Select>
            </Form.Item>
          </Col>
        </Row>
        <Row className={styles.inputItem}>
          <Col className={styles.itemLabel} span={8}>
            开户行：
          </Col>
          <Col className={styles.inputTextContent} span={16}>
            <Form.Item
              name="bankOfDeposit"
              rules={[
                { required: true, message: '开户行不能为空' },
              ]}
            >
              <Input placeholder="请输入开户行" />
            </Form.Item>
          </Col>
        </Row>
        <Row className={styles.inputItem}>
          <Col className={styles.itemLabel} span={8}>
            对公账户：
          </Col>
          <Col className={styles.inputTextContent} span={16}>
            <Form.Item
              name="corporateAccount"
              rules={[
                { required: true, message: '对公账户不能为空' },
              ]}
            >
              <Input placeholder="请输入对公账户" />
            </Form.Item>
          </Col>
        </Row>
        <Row className={styles.inputItem}>
          <Col className={styles.itemLabel} span={8}>
            法人姓名：
          </Col>
          <Col className={styles.inputTextContent} span={16}>
            <Form.Item name="legalPerson" rules={[{ required: true, message: '法人姓名不能为空' }]}>
              <Input placeholder="请输入法人姓名" />
            </Form.Item>
          </Col>
        </Row>
        <Row className={styles.inputItem}>
          <Col className={styles.itemLabel} span={8}>
            法人电话：
          </Col>
          <Col className={styles.inputTextContent} span={16}>
            <Form.Item
              name="legalPersonPhone"
              rules={[
                {
                  required: true,
                  message: '法人电话不能为空',
                },
                {
                  pattern: /^1\d{10}$/,
                  message: '手机号格式错误！',
                },
              ]}
            >
              <Input placeholder="请输入法人电话" />
            </Form.Item>
          </Col>
        </Row>
        <Row className={styles.inputItem}>
          <Col className={styles.itemLabel} span={8}>
            联系人1姓名：
          </Col>
          <Col className={styles.inputTextContent} span={16}>
            <Form.Item name="userName" rules={[{ required: true, message: '联系人姓名不能为空' }]}>
              <Input placeholder="请输入联系人姓名" />
            </Form.Item>
          </Col>
        </Row>
        <Row className={styles.inputItem}>
          <Col className={styles.itemLabel} span={8}>
            联系人1职务：
          </Col>
          <Col className={styles.inputTextContent} span={16}>
            <Form.Item name="contactJob" rules={[{ required: true, message: '联系人职务不能为空' }]}>
              <Input placeholder="请输入联系人职务" />
            </Form.Item>
          </Col>
        </Row>
        <Row className={styles.inputItem}>
          <Col className={styles.itemLabel} span={8}>
            联系人1电话：
          </Col>
          <Col className={styles.inputTextContent} span={16}>
            <Form.Item
              name="phone"
              rules={[
                {
                  required: true,
                  message: '联系方式不能为空',
                },
                {
                  pattern: /^1\d{10}$/,
                  message: '手机号格式错误！',
                },
              ]}
            >
              <Input placeholder="请输入联系方式" />
            </Form.Item>
          </Col>
        </Row>
        <Row className={styles.inputItem}>
          <Col className={styles.itemLabel} span={8}>
            联系人2姓名：
          </Col>
          <Col className={styles.inputTextContent} span={16}>
            <Form.Item name="contactTwoName" rules={[{ required: true, message: '联系人姓名不能为空' }]}>
              <Input placeholder="请输入联系人姓名" />
            </Form.Item>
          </Col>
        </Row>
        <Row className={styles.inputItem}>
          <Col className={styles.itemLabel} span={8}>
            联系人2职务：
          </Col>
          <Col className={styles.inputTextContent} span={16}>
            <Form.Item name="contactTwoJob" rules={[{ required: true, message: '联系人职务不能为空' }]}>
              <Input placeholder="请输入联系人职务" />
            </Form.Item>
          </Col>
        </Row>
        <Row className={styles.inputItem}>
          <Col className={styles.itemLabel} span={8}>
            联系人2电话：
          </Col>
          <Col className={styles.inputTextContent} span={16}>
            <Form.Item
              name="contactTwoPhone"
              rules={[
                {
                  required: true,
                  message: '联系方式不能为空',
                },
                {
                  pattern: /^1\d{10}$/,
                  message: '手机号格式错误！',
                },
              ]}
            >
              <Input placeholder="请输入联系方式" />
            </Form.Item>
          </Col>
        </Row>
        <Row className={styles.inputItem}>
          <Col className={styles.itemLabel} span={8}>
            邮箱：
          </Col>
          <Col className={styles.inputTextContent} span={16}>
            <Form.Item
              name="email"
              rules={[
                {
                  pattern:
                    /^[a-zA-Z0-9]+([-_.][a-zA-Z0-9]+)*@[a-zA-Z0-9]+([-_.][a-zA-Z0-9]+)*\.[a-z]{2,}$/,
                  message: '邮箱格式错误',
                },
              ]}
            >
              <Input placeholder="请输入邮箱" />
            </Form.Item>
          </Col>
        </Row>
        <div className={styles.submitButton}>
          <Button type="primary" onClick={handleSubmit}>
            提交
          </Button>
        </div>
      </Form>
    </div>
  );
};
export default connect(({ login }: any) => ({
  isLogin: login.isLogin,
}))(UserRegister);
